// pages/printer-settings/printer-settings.ts
import { MerchantAPI } from '../../utils/api'

interface Printer {
  printerId: number;
  printerName: string;
  printerBrand: string;
  printerModel: string;
  printerSn: string;
  connectionType: number;
  ipAddress?: string;
  port?: number;
  printWidth: number;
  autoPrintOrder: number;
  printCopies: number;
  isDefault: number;
  isOnline: number;
  status: number;
  statusText: string;
  connectionTypeText: string;
}

Page({
  data: {
    statusBarHeight: 0,
    printers: [] as Printer[],
    loading: false,
    showAddModal: false,
    showEditModal: false,
    currentPrinter: null as Printer | null,
    activeFieldId: '',
    formScrollTopAdd: 0,
    formScrollTopEdit: 0,
    scrollOffsetAdd: 0,
    scrollOffsetEdit: 0,
    
    // 新增/编辑表单数据
    formData: {
      printerName: '',
      printerBrand: '',
      printerModel: '',
      printerSn: '',
      printerKey: '',
      connectionType: 1,  // 1-云打印，2-蓝牙，3-WiFi，4-USB
      ipAddress: '',
      port: 9100,
      printWidth: 58,
      autoPrintOrder: 1,
      printCopies: 1
    },
    
    // 品牌选项
    brandOptions: ['飞鹅', '易联云', '其他'],
    connectionTypeOptions: [
      { label: '云打印', value: 1 },
      { label: '蓝牙', value: 2 },
      { label: 'WiFi', value: 3 },
      { label: 'USB', value: 4 }
    ]
  },

  onLoad() {
    this.setData({
      statusBarHeight: wx.getSystemInfoSync().statusBarHeight || 0
    });
    this.loadPrinters();
  },

  onShow() {
    this.loadPrinters();
  },

  /**
   * 加载打印机列表
   */
  async loadPrinters() {
    this.setData({ loading: true });
    
    try {
      const result = await MerchantAPI.getPrinterList();
      
      if (result && result.data) {
        const printers: Printer[] = result.data.map((item: any) => ({
          printerId: item.printerId || item.printer_id,
          printerName: item.printerName || item.printer_name,
          printerBrand: item.printerBrand || item.printer_brand,
          printerModel: item.printerModel || item.printer_model,
          printerSn: item.printerSn || item.printer_sn,
          connectionType: item.connectionType || item.connection_type || 1,
          ipAddress: item.ipAddress || item.ip_address,
          port: item.port,
          printWidth: item.printWidth || item.print_width || 58,
          autoPrintOrder: item.autoPrintOrder || item.auto_print_order || 1,
          printCopies: item.printCopies || item.print_copies || 1,
          isDefault: item.isDefault || item.is_default || 0,
          isOnline: item.isOnline || item.is_online || 0,
          status: item.status || 0,
          statusText: this.getStatusText(item.status || 0),
          connectionTypeText: this.getConnectionTypeText(item.connectionType || item.connection_type || 1)
        }));
        
        this.setData({ printers });
      }
    } catch (error: any) {
      console.error('加载打印机列表失败', error);
      wx.showToast({
        title: error.msg || '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 获取状态文本
   */
  getStatusText(status: number): string {
    const statusMap: Record<number, string> = {
      0: '停用',
      1: '启用',
      2: '维护中'
    };
    return statusMap[status] || '未知';
  },

  /**
   * 获取连接方式文本
   */
  getConnectionTypeText(type: number): string {
    const typeMap: Record<number, string> = {
      1: '云打印',
      2: '蓝牙',
      3: 'WiFi',
      4: 'USB'
    };
    return typeMap[type] || '未知';
  },

  /**
   * 显示添加打印机弹窗
   */
  showAddPrinter() {
    this.setData({
      showAddModal: true,
      formData: {
        printerName: '',
        printerBrand: '',
        printerModel: '',
        printerSn: '',
        printerKey: '',
        connectionType: 1,
        ipAddress: '',
        port: 9100,
        printWidth: 58,
        autoPrintOrder: 1,
        printCopies: 1
      }
    });
  },

  /**
   * 显示编辑打印机弹窗
   */
  showEditPrinter(e: any) {
    const printerId = e.currentTarget.dataset.id;
    const printer = this.data.printers.find(p => p.printerId === printerId);
    
    if (printer) {
      this.setData({
        showEditModal: true,
        currentPrinter: printer,
        formData: {
          printerName: printer.printerName,
          printerBrand: printer.printerBrand,
          printerModel: printer.printerModel,
          printerSn: printer.printerSn,
          printerKey: '',
          connectionType: printer.connectionType,
          ipAddress: printer.ipAddress || '',
          port: printer.port || 9100,
          printWidth: printer.printWidth,
          autoPrintOrder: printer.autoPrintOrder,
          printCopies: printer.printCopies
        }
      });
    }
  },

  /**
   * 关闭弹窗
   */
  closeModal() {
    this.setData({
      showAddModal: false,
      showEditModal: false,
      currentPrinter: null
    });
  },

  /**
   * 表单输入处理
   */
  onFormInput(e: any) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    
    this.setData({
      [`formData.${field}`]: value
    });
  },

  /**
   * 选择连接方式
   */
  onConnectionTypeChange(e: any) {
    this.setData({
      'formData.connectionType': parseInt(e.detail.value) + 1
    });
  },

  /**
   * 选择打印纸宽度
   */
  onPrintWidthChange(e: any) {
    const width = parseInt(e.detail.value) === 0 ? 58 : 80;
    this.setData({
      'formData.printWidth': width
    });
  },

  /**
   * 自动打印开关
   */
  onAutoPrintChange(e: any) {
    this.setData({
      'formData.autoPrintOrder': e.detail.value ? 1 : 0
    });
  },

  /**
   * 输入聚焦时滚动到对应表单项
   */
  onFieldFocus(e: any) {
    const target = e.currentTarget.dataset.target;
    const mode = e.currentTarget.dataset.mode || 'add';
    if (!target) return;

    const scrollSelector = mode === 'edit' ? '#edit-scroll' : '#add-scroll';
    const query = wx.createSelectorQuery().in(this);
    query.select(scrollSelector).boundingClientRect();
    query.select(`#${target}`).boundingClientRect();
    query.exec(res => {
      const scrollRect = res?.[0];
      const targetRect = res?.[1];

      if (!scrollRect || !targetRect) {
        this.setData({ activeFieldId: target });
        return;
      }

      const currentScroll = mode === 'edit' ? this.data.scrollOffsetEdit : this.data.scrollOffsetAdd;
      const relativeTop = targetRect.top - scrollRect.top;
      const desired = Math.max(currentScroll + relativeTop - 40, 0);

      if (mode === 'edit') {
        this.setData({
          activeFieldId: target,
          formScrollTopEdit: desired
        });
      } else {
        this.setData({
          activeFieldId: target,
          formScrollTopAdd: desired
        });
      }
    });
  },

  onFieldBlur() {
    this.setData({
      activeFieldId: ''
    });
  },

  onFormScroll(e: any) {
    const mode = e.currentTarget.dataset.scroll || 'add';
    if (mode === 'edit') {
      this.setData({ scrollOffsetEdit: e.detail.scrollTop });
    } else {
      this.setData({ scrollOffsetAdd: e.detail.scrollTop });
    }
  },

  /**
   * 提交新增打印机
   */
  async submitAddPrinter() {
    const { formData } = this.data;
    
    // 验证必填字段
    if (!formData.printerName.trim()) {
      wx.showToast({ title: '请输入打印机名称', icon: 'none' });
      return;
    }
    if (!formData.printerBrand.trim()) {
      wx.showToast({ title: '请输入打印机品牌', icon: 'none' });
      return;
    }
    if (!formData.printerModel.trim()) {
      wx.showToast({ title: '请输入打印机型号', icon: 'none' });
      return;
    }
    if (!formData.printerSn.trim()) {
      wx.showToast({ title: '请输入打印机序列号', icon: 'none' });
      return;
    }
    
    wx.showLoading({ title: '添加中...' });
    
    try {
      await MerchantAPI.addPrinter({
        printerName: formData.printerName,
        printerBrand: formData.printerBrand,
        printerModel: formData.printerModel,
        printerSn: formData.printerSn,
        printerKey: formData.printerKey || undefined,
        connectionType: formData.connectionType,
        ipAddress: formData.ipAddress || undefined,
        port: formData.port || undefined,
        printWidth: formData.printWidth,
        autoPrintOrder: formData.autoPrintOrder,
        printCopies: formData.printCopies
      });
      
      wx.hideLoading();
      wx.showToast({
        title: '添加成功',
        icon: 'success'
      });
      
      this.closeModal();
      this.loadPrinters();
      
    } catch (error: any) {
      wx.hideLoading();
      wx.showToast({
        title: error.msg || '添加失败',
        icon: 'none'
      });
    }
  },

  /**
   * 提交编辑打印机
   */
  async submitEditPrinter() {
    const { formData, currentPrinter } = this.data;
    
    if (!currentPrinter) return;
    
    // 验证必填字段
    if (!formData.printerName.trim()) {
      wx.showToast({ title: '请输入打印机名称', icon: 'none' });
      return;
    }
    if (!formData.printerBrand.trim()) {
      wx.showToast({ title: '请输入打印机品牌', icon: 'none' });
      return;
    }
    if (!formData.printerModel.trim()) {
      wx.showToast({ title: '请输入打印机型号', icon: 'none' });
      return;
    }
    if (!formData.printerSn.trim()) {
      wx.showToast({ title: '请输入打印机序列号', icon: 'none' });
      return;
    }
    
    wx.showLoading({ title: '保存中...' });
    
    try {
      await MerchantAPI.updatePrinter({
        printerId: currentPrinter.printerId,
        printerName: formData.printerName,
        printerBrand: formData.printerBrand,
        printerModel: formData.printerModel,
        printerSn: formData.printerSn,
        printerKey: formData.printerKey || undefined,
        connectionType: formData.connectionType,
        ipAddress: formData.ipAddress || undefined,
        port: formData.port || undefined,
        printWidth: formData.printWidth,
        autoPrintOrder: formData.autoPrintOrder,
        printCopies: formData.printCopies
      });
      
      wx.hideLoading();
      wx.showToast({
        title: '保存成功',
        icon: 'success'
      });
      
      this.closeModal();
      this.loadPrinters();
      
    } catch (error: any) {
      wx.hideLoading();
      wx.showToast({
        title: error.msg || '保存失败',
        icon: 'none'
      });
    }
  },

  /**
   * 设置默认打印机
   */
  async setDefaultPrinter(e: any) {
    const printerId = e.currentTarget.dataset.id;
    
    wx.showLoading({ title: '设置中...' });
    
    try {
      await MerchantAPI.setDefaultPrinter(printerId);
      
      wx.hideLoading();
      wx.showToast({
        title: '设置成功',
        icon: 'success'
      });
      
      this.loadPrinters();
      
    } catch (error: any) {
      wx.hideLoading();
      wx.showToast({
        title: error.msg || '设置失败',
        icon: 'none'
      });
    }
  },

  /**
   * 更新打印机状态
   */
  async togglePrinterStatus(e: any) {
    const printerId = e.currentTarget.dataset.id;
    const printer = this.data.printers.find(p => p.printerId === printerId);
    
    if (!printer) return;
    
    const newStatus = printer.status === 1 ? 0 : 1;
    
    wx.showLoading({ title: '更新中...' });
    
    try {
      await MerchantAPI.updatePrinterStatus(printerId, newStatus);
      
      wx.hideLoading();
      wx.showToast({
        title: newStatus === 1 ? '已启用' : '已停用',
        icon: 'success'
      });
      
      this.loadPrinters();
      
    } catch (error: any) {
      wx.hideLoading();
      wx.showToast({
        title: error.msg || '操作失败',
        icon: 'none'
      });
    }
  },

  /**
   * 测试打印
   */
  async testPrint(e: any) {
    const printerId = e.currentTarget.dataset.id;
    
    wx.showLoading({ title: '测试打印中...' });
    
    try {
      await MerchantAPI.testPrint(printerId);
      
      wx.hideLoading();
      wx.showToast({
        title: '测试打印成功',
        icon: 'success'
      });
      
    } catch (error: any) {
      wx.hideLoading();
      wx.showToast({
        title: error.msg || '测试打印失败',
        icon: 'none'
      });
    }
  },

  /**
   * 删除打印机
   */
  deletePrinter(e: any) {
    const printerId = e.currentTarget.dataset.id;
    const printer = this.data.printers.find(p => p.printerId === printerId);
    
    if (!printer) return;
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除打印机"${printer.printerName}"吗？`,
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...' });
          
          try {
            await MerchantAPI.deletePrinter(printerId);
            
            wx.hideLoading();
            wx.showToast({
              title: '删除成功',
              icon: 'success'
            });
            
            this.loadPrinters();
            
          } catch (error: any) {
            wx.hideLoading();
            wx.showToast({
              title: error.msg || '删除失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  goBack() {
    wx.navigateBack();
  },

  preventClose() {
    // 阻止事件冒泡
  }
});
